/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package todotask.Database;

import java.awt.Color;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import todotask.core.Fecha;
import todotask.core.Hex2Decimal;
import todotask.entities.Category;
import todotask.entities.Status;
import todotask.entities.Task;

/**
 *
 * @author dakota
 */
public class Data {

    private Database db;

    public static void main(String args[]) {
//        new Data().getTaskPending();
    }

    public Data() {
        try {
            db = new Database();
        } catch (InstantiationException ex) {
            Logger.getLogger(Data.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Data.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Data.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Data.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Task[] getTaskPending() throws SQLException {
        String query = "select * from task,status,category where status_idstatus!=(select idstatus from status where status='Finalizado') and task.status_idstatus=status.idstatus and task.category_idcategory=category.idcategory";
        ArrayList<Task> list = new ArrayList<Task>();
        Task t;
        ResultSet rs = db.consulta(query);


        while (rs.next()) {
            t = new Task();
            t.setTitle(rs.getString("title"));
            t.setDescription(rs.getString("description"));
            try {
                t.setStartDate(new Fecha(rs.getString("start_date")).parseDate());
            } catch (Exception ex) {
                t.setStartDate(Calendar.getInstance());
            }
            try {
                t.setFinishDate(new Fecha(rs.getString("finish_date")).parseDate());
            } catch (Exception ex) {
                t.setFinishDate(null);
            }
            t.setStatus(new Status(rs.getString("status")));
            t.setId(rs.getString("idTask"));
            String rgb = rs.getString("color");

            String rr = rgb.substring(0, 1);
            String gg = rgb.substring(1, 3);
            String bb = rgb.substring(3, 5);

            Integer r_ = new Integer(Hex2Decimal.hex2decimal(rr));
            Float r = new Float(r_.toString());

            Integer g_ = new Integer(Hex2Decimal.hex2decimal(gg));
            Float g = new Float(g_.toString());

            Integer b_ = new Integer(Hex2Decimal.hex2decimal(bb));
            Float b = new Float(b_.toString());

            t.setCategory(new Category(rs.getString("category"), Color.getHSBColor(r, g, b)));
            t.setTime(Integer.parseInt(rs.getString("time")));
            list.add(t);
        }

        Object[] cat = list.toArray();
        Task[] c = new Task[cat.length];
        int i = 0;
        for (Object o : cat) {
            if (o instanceof Task) {
                c[i] = (Task) o;
                i++;
            }
        }
        return c;

//        return (Task[]) list.toArray();
    }

    /**
     * Conseguimos todos los estados de la base de datos
     * 
     * @return
     * @throws SQLException 
     */
    public Status[] getStatus() throws SQLException {
        String query = "select * from status";
        ArrayList<Status> list = new ArrayList<Status>();
        Status st;
        ResultSet rs = db.consulta(query);

        while (rs.next()) {
            st = new Status();
            st.setStatus(rs.getString("status"));
            st.setId(Integer.parseInt(rs.getString("idstatus")));
            list.add(st);
        }

        for (Status tt : list) {
            System.out.println(tt.toString());
        }

        Object[] cat = list.toArray();
        Status[] c = new Status[cat.length];
        int i = 0;
        for (Object o : cat) {
            if (o instanceof Status) {
                c[i] = (Status) o;
                i++;
            }
        }
        return c;
    }

    /**
     * Guarda una tarea con con la fecha de comienzo del dia de hoy
     * 
     * @param t
     * @return 
     */
    public boolean saveTask(Task t) {

        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH);
        month++;
        String start = c.get(Calendar.YEAR) + "-" + month + "-" + c.get(Calendar.DAY_OF_MONTH);

        String query = "select * from task where idtask=" + t.getId();
        ResultSet rs = db.consulta(query);
        try {
            if (rs.next()) {
                query = "update task set title='" + t.getTitle() + "',description='" + t.getDescription()
                        + "', category_idcategory=" + t.getCategory().getId() + ", status_idstatus="
                        + t.getStatus().getId() + "";
                return db.ejecuta(query);
            } else {

                query = "insert into task values(0,'" + t.getTitle() + "','" + t.getDescription()
                        + "'," + t.getTime() + ",'" + start + "',null," + t.getCategory().getId() + ","
                        + t.getStatus().getId() + ")";

                return db.ejecuta(query);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Data.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    /**
     * Conseguimos las categorias de la base de datos
     * 
     * @return
     * @throws SQLException 
     */
    public Category[] getCategories() throws SQLException {
        String query = "select * from category";
        ArrayList<Category> list = new ArrayList<Category>();
        Category st;
        ResultSet rs = db.consulta(query);

        while (rs.next()) {
            st = new Category();
            st.setId(Integer.parseInt(rs.getString("idcategory")));
            st.setNombre(rs.getString("category"));
            String rgb = rs.getString("color");

            String rr = rgb.substring(0, 1);
            String gg = rgb.substring(1, 3);
            String bb = rgb.substring(3, 5);

            Integer r_ = new Integer(Hex2Decimal.hex2decimal(rr));
            Float r = new Float(r_.toString());

            Integer g_ = new Integer(Hex2Decimal.hex2decimal(gg));
            Float g = new Float(g_.toString());

            Integer b_ = new Integer(Hex2Decimal.hex2decimal(bb));
            Float b = new Float(b_.toString());

            st.setColor(Color.getHSBColor(r, g, b));


            System.out.println(st.getColor());
            list.add(st);
        }

        Object[] cat = list.toArray();
        Category[] c = new Category[cat.length];
        int i = 0;
        for (Object o : cat) {
            if (o instanceof Category) {
                c[i] = (Category) o;
                i++;
            }
        }
        return c;
    }

    public boolean setFinished(Task t) {
        String query = "update task set finish_date='" + t.getFinishDate().YEAR + "/"
                + t.getFinishDate().MONTH + "/" + t.getFinishDate().DAY_OF_MONTH + "' where idtask="
                + t.getId();
        return db.ejecuta(query);

    }
}
